# coding=utf-8

#python
import os
import random
import logging

#appengine
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template

#lib
from const import *

#handlers
class URLHandler(webapp.RequestHandler):
    def get(self):
        #collect all query parameters
        query_parameters = self.request.arguments() 
        #check URL variations parameters
        variations_parameters = [p for p in query_parameters if p[:len(PARAM_URLS_PREFIX)]==PARAM_URLS_PREFIX]
        #add to system parameters list
        SYS_PARAMETERS.extend(variations_parameters)
        
        #extract all URLs to randomize
        variations = [{'index':param_name.replace(PARAM_URLS_PREFIX,""), 'url':self.request.get(param_name)} for param_name in variations_parameters]

        #persistence
        persistence = self.request.get_range(PARAM_PERSISTENCE, min_value=0, max_value=MAX_PERSISTENCE_MS, default=PERSISTENCE_MS)

        #variations - required
        if len(variations) > 0 :          
            
            #randomize variation
            variation_choice = random.sample(variations,1)[0]
            final_url = variation_choice['url']
            
            #check protocol
            if final_url[:4].lower()!='http':
                final_url = '//' + final_url

            #extract original query, excluding system parameters
            params = [p for p in query_parameters if p not in SYS_PARAMETERS]
            params_pairs = []
            for param in params:
                param_values = self.request.get_all(param)
                for param_value in param_values:
                    params_pairs.append("%s=%s" % (param, param_value))
            query = "&".join(params_pairs)
            #add query to final url
            if final_url.find("?")==-1: 
                final_url += '?' + query
            else:
                final_url += '&' + query
            #append variation parameter
            final_url += "&%s=%s" % (PARAM_URLS_PREFIX, variation_choice['index'])
            
            #redirect to the final destination
            logging.debug("final_url:%s", str(final_url))
            self.redirect(final_url)


application = webapp.WSGIApplication(
                                     [('.+', URLHandler)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
